package org.rcy.framework.thrift.serializer;

import net.qiyuesuo.rpc.thrift.metadata.FieldValueMetaData;
import net.qiyuesuo.rpc.thrift.metadata.ListMetaData;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TList;
import org.apache.thrift.protocol.TProtocol;

import java.util.ArrayList;
import java.util.List;

public class ListSerializer implements Serializer {

	@Override
	public Object read(TProtocol iprot, FieldValueMetaData valueMetaData) throws TException {
		ListMetaData listMetaData = (ListMetaData) valueMetaData;

		TList list = iprot.readListBegin();
		List<Object> success = new ArrayList(list.size);
		for (int i = 0; i < list.size; i++) {
			Object element = ThriftSerializer.read(iprot, listMetaData.elemMetaData);
			success.add(element);
		}
		iprot.readListEnd();
		return success;
	}

	@Override
	public void write(TProtocol oprot, FieldValueMetaData valueMetaData, Object value) throws TException {
		ListMetaData listMetaData = (ListMetaData) valueMetaData;
		FieldValueMetaData elemMetaData = listMetaData.elemMetaData;
		List list = (List) value;

		oprot.writeListBegin(new TList(elemMetaData.type, list.size()));
		for (Object object : list) {
			ThriftSerializer.write(oprot, elemMetaData, object);
		}
		oprot.writeListEnd();
	}
}
